//
//  CreateScreen.m
//  Playlist
//
//  Created by bfduran on 12/1/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CreateScreen.h"


@implementation CreateScreen
@synthesize playListName;
@synthesize isEditScreen;
@synthesize addSong;
@synthesize deleteSong;
@synthesize title;
@synthesize savePlaylist;
@synthesize selectedSongs;

@synthesize tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Change the label in the nav controller
    if(isEditScreen)
    {
        [self.navigationItem setTitle:playListName];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *location = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@.stuff", playListName];
        selectedSongs = [NSKeyedUnarchiver unarchiveObjectWithFile:location];
        title.text = playListName;
        [selectedSongs retain];
    }
    else
    {
        [self.navigationItem setTitle:@"Create Playlist"];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


//---------------------------------------------------------------------------------------------
-(IBAction) addSongButtonPressed
{    
    if([title.text isEqualToString: @""])
    {
        title.placeholder = @"Enter text, homes!";
        title.textColor = [UIColor whiteColor];
        title.backgroundColor = [UIColor redColor];
    }
    else
    {
        title.placeholder = @"Enter Playlist Name";
        title.textColor = [UIColor blackColor];
        title.backgroundColor = [UIColor whiteColor];
    
        
        //Show the media picker somehow -_-
        MPMediaPickerController * musicPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAny];
        musicPicker.delegate = self;
        musicPicker.allowsPickingMultipleItems = YES;
        musicPicker.prompt = @"Select songs for playlist";
        [self presentModalViewController:musicPicker animated:YES];
        [musicPicker release];
    }
    
}

//Extends the didPickMediaItem function to handle actually grabbing media
-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
    if (selectedSongs == nil)
    {
        selectedSongs = mediaItemCollection;
        [selectedSongs retain];
    }
    else
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        [tempArray addObjectsFromArray:selectedSongs.items];
        [tempArray addObjectsFromArray:mediaItemCollection.items];
                
        selectedSongs = [[MPMediaItemCollection alloc] initWithItems:tempArray];
    }
    
    //Close the media picker
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSData *dummy = [NSKeyedArchiver archivedDataWithRootObject: selectedSongs];
    NSString *location = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@.stuff", playListName];
    
    [dummy writeToFile:location atomically:YES];
    
    [self dismissModalViewControllerAnimated:YES];
    
    [tableView reloadData];
}

-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction) deleteSongButtonPressed
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *location = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@.stuff", playListName];
    MPMediaItemCollection * bart = [NSKeyedUnarchiver unarchiveObjectWithFile:location];
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    [tempArray addObjectsFromArray:bart.items];
    [tempArray removeObject:currentSong];
    
    [selectedSongs initWithItems:tempArray];
    NSData *dummy = [NSKeyedArchiver archivedDataWithRootObject:selectedSongs];
    
    [dummy writeToFile:location atomically:YES];
    
    [tableView reloadData];
}

-(BOOL)textFieldShouldReturn:(UITextField *) textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    playListName = textField.text;
    [textField resignFirstResponder];
    [self addSongButtonPressed];
}

- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    cell.textLabel.text = [[selectedSongs.items objectAtIndex:indexPath.row] valueForProperty:MPMediaItemPropertyTitle];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (selectedSongs == nil)
        return 0;
    return [selectedSongs count];
}

- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    currentSong = [selectedSongs.items objectAtIndex:indexPath.row];
}



@end
